﻿

using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Text;
using System.Web.Caching;

using Maticsoft.DBUtility;
using Utils;
using System.IO;

/// <summary>
///API 的摘要说明
/// </summary>
public partial class api : FBasePage
{
    // Fields
    protected string cityename = string.Empty;
    protected DataTable teamtable = new DataTable();

    // Methods
    private string ConvertAPI(string api)
    {
        int num2;
        string str6;
        Regex regex2;
        MatchCollection matchs;
        int num3;
        string str7;
        string str8;
        bool flag;
        int @int;
        NameValueCollection values = new NameValueCollection();
        values.Add("网站名称", "<![CDATA[" + base.ASSystem.sitename + "]]>");
        values.Add("网站地址", base.WWWprefix);
        values.Add("当前日期", DateTime.Now.ToString("yyyy-MM-dd"));
        values.Add("版本号", 1.0M.ToString());
        if (api == string.Empty)
        {
            return string.Empty;
        }
        Regex regex = new Regex(@"\r?\n?<!--loop-->((.|\s)+?)<!--end-->\r?\n?");
        Match match = regex.Match(api);
        string replacement = regex.Replace(match.Value, "$1");
        StringBuilder builder = new StringBuilder();
        string tablename = "(select t2.*,title,homepage,Contact,Phone,Address,location from (select t1.*,Category.Name as groupname from(select Team.Id as teamid,Category.Name as cityname,Team.Product as productname,Team.Image,team.Partner_id,Team.Begin_time,Team.End_time,Team.Market_price,Team.Team_price,Team.Now_number,Per_number,Min_number,Team.Summary,Team.Detail,Team.Group_id from Team left join Category on(Team.City_id=Category.Id) where Team.Begin_time<='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' and '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'<=Team.End_time and Team.Team_type='normal' and ((Team.Max_number>0 and Team.Now_number<Team.Max_number)or(Team.Max_number=0)))  t1 left join Category on(t1.Group_id=Category.Id)) as t2 left join partner on t2.Partner_id=partner.id) t3";
        if ((this.cityename != string.Empty) && (this.cityename.ToLower() != "quanguo"))
        {
            tablename = "(select t2.*,title,homepage,Contact,Phone,Address,location from (select t1.*,Category.Name as groupname from(select Team.Id as teamid,Category.Name as cityname,Team.Product as productname,Team.Image,team.Partner_id,Team.Begin_time,Team.End_time,Team.Market_price,Team.Team_price,Team.Now_number,Per_number,Min_number,Team.Summary,Team.Detail,Team.Group_id from Team left join Category on(Team.City_id=Category.Id) where Category.ename='" + this.cityename + "' and Team.Begin_time<='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' and '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'<=Team.End_time and Team.Team_type='normal' and ((Team.Max_number>0 and Team.Now_number<Team.Max_number)or(Team.Max_number=0)))  t1 left join Category on(t1.Group_id=Category.Id)) as t2 left join partner on t2.Partner_id=partner.id) t3";
        }
        this.teamtable = DbHelperSQL.SelectByFilter("*", string.Empty, "Begin_time desc", tablename);
        for (int i = 0; i < this.teamtable.Rows.Count; i++)
        {
            DataRow row = this.teamtable.Rows[i];
            NameValueCollection values2 = new NameValueCollection();
            values2.Add("分类", row["groupname"].ToString());
            values2.Add("最小成团人数", row["Min_number"].ToString());
            values2.Add("限购数量", row["Per_number"].ToString());
            values2.Add("已购人数", row["now_number"].ToString());
            values2.Add("商品描述", "<![CDATA[" + row["Detail"].ToString() + "]]>");
            values2.Add("商品简介", "<![CDATA[" + row["Summary"].ToString() + "]]>");
            values2.Add("折扣", WebSiteHelper.GetDiscount(Convert.ToDecimal(row["Market_price"]), Convert.ToDecimal(row["Team_price"])).Replace("折", ""));
            values2.Add("团购价", row["Team_price"].ToString());
            values2.Add("市场价", row["Market_price"].ToString());
            values2.Add("结束时间年月日时分秒", Convert.ToDateTime(row["End_time"]).ToString("yyyyMMddHHmmss"));
            values2.Add("开始时间年月日时分秒", Convert.ToDateTime(row["Begin_time"]).ToString("yyyyMMddHHmmss"));
            values2.Add("开始时间戳", Helper.GetTimeFix(Convert.ToDateTime(row["Begin_time"])).ToString());
            values2.Add("结束时间戳", Helper.GetTimeFix(Convert.ToDateTime(row["End_time"])).ToString());
            values2.Add("结束时间年-月-日 时:分:秒", Convert.ToDateTime(row["End_time"]).ToString("yyyy-MM-dd HH:mm:ss"));
            values2.Add("开始时间年-月-日 时:分:秒", Convert.ToDateTime(row["Begin_time"]).ToString("yyyy-MM-dd HH:mm:ss"));
            values2.Add("项目ID", row["teamid"].ToString());
            string str3 = row["image"].ToString();
            if (str3.Length > 0)
            {
                str3 = str3.Substring(1);
            }
            values2.Add("商品图片", base.WWWprefix + str3);
            values2.Add("商品名称", "<![CDATA[" + row["productname"].ToString() + "]]>");
            string str4 = row["cityname"].ToString();
            if (str4 == "全国")
            {
                str4 = string.Empty;
            }
            values2.Add("城市", str4);
            if (str4 == string.Empty)
            {
                values2.Add("城市必", "全国");
            }
            else
            {
                values2.Add("城市必", str4);
            }
            values2.Add("项目地址", base.WWWprefix + "team.aspx?id=" + row["teamid"]);
            values2.Add("商户名称", "<![CDATA[" + row["title"].ToString() + "]]>");
            values2.Add("商户网站", "<![CDATA[" + row["homepage"].ToString() + "]]>");
            values2.Add("商户联系人", "<![CDATA[" + row["contact"].ToString() + "]]>");
            values2.Add("商户联系电话", "<![CDATA[" + row["phone"].ToString() + "]]>");
            values2.Add("商户联系地址", "<![CDATA[" + row["address"].ToString() + "]]>");
            string input = replacement;
            num2 = 0;
            while (num2 < values2.Keys.Count)
            {
                str6 = values2.Keys[num2];
                regex2 = new Regex("{(" + str6 + ")}|{(" + str6 + @"),(\d+)}");
                matchs = regex2.Matches(input);
                num3 = 0;
                while (num3 < matchs.Count)
                {
                    str7 = Helper.GetString(values2[str6], string.Empty);
                    str8 = regex2.Replace(matchs[num3].Value, "$3");
                    flag = false;
                    if (str8 != string.Empty)
                    {
                        @int = Helper.GetInt(str8, 0);
                        if (@int > 0)
                        {
                            input = input.Replace(matchs[num3].Value, "<![CDATA[" + Helper.SubString(str7.Replace("<![CDATA[", "").Replace("]]>", ""), @int * 2) + "]]>");
                            flag = true;
                        }
                    }
                    if (!flag)
                    {
                        input = input.Replace(matchs[num3].Value, str7);
                    }
                    num3++;
                }
                num2++;
            }
            builder.Append(input);
        }
        replacement = builder.ToString();
        api = regex.Replace(api, replacement);
        for (num2 = 0; num2 < values.Keys.Count; num2++)
        {
            str6 = values.Keys[num2];
            regex2 = new Regex(@"\{(" + str6 + @")\}|\{(" + str6 + @"),(\d+)\}");
            matchs = regex2.Matches(api);
            str7 = Helper.GetString(values[str6], string.Empty);
            num3 = 0;
            while (num3 < matchs.Count)
            {
                str8 = regex2.Replace(matchs[num3].Value, "$3");
                flag = false;
                if (str8 != string.Empty)
                {
                    @int = Helper.GetInt(str8, 0);
                    if (@int > 0)
                    {
                        api = api.Replace(matchs[num3].Value, Helper.SubString(str7, @int * 2));
                        flag = true;
                    }
                }
                if (!flag)
                {
                    api = api.Replace(matchs[num3].Value, str7);
                }
                num3++;
            }
        }
        api = api.Replace("{城市必}", "全国");
        Regex regex3 = new Regex(@"\{(编号)\}");
        MatchCollection matchs2 = regex3.Matches(api);
        for (num3 = 0; num3 < matchs2.Count; num3++)
        {
            api = regex3.Replace(api, (num3 + 1).ToString(), 1);
        }
        return api;
    }

    private string GetAPI(string name)
    {
        string str = string.Empty;
        if (name == string.Empty)
        {
            return str;
        }
        object obj2 = HttpContext.Current.Cache[name];
        if (obj2 == null)
        {
            string path = base.Server.MapPath("~/apitemplate/" + name + ".htm");
            if (File.Exists(path))
            {
                str = File.ReadAllText(path);
                HttpContext.Current.Cache.Add(name, str, new CacheDependency(path), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }
            return str;
        }
        return obj2.ToString();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.Response.ContentType = "text/xml";
        string name = Helper.GetString(base.Request["key"], string.Empty);
        string str2 = Helper.GetString(base.Request["code"], string.Empty);
        this.cityename = Helper.GetString(base.Request["city"], string.Empty);
        if (name != string.Empty)
        {
            string aPI = this.GetAPI(name);
            if (str2 != "gb2312")
            {
                aPI = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + aPI;
            }
            else
            {
                aPI = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\r\n" + aPI;
                base.Response.HeaderEncoding = Encoding.GetEncoding("GB2312");
                base.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            }
            base.Response.Write(this.ConvertAPI(aPI));
        }
        base.Response.End();
    }
}
